package com.cnap.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.cnap.config.UserSysConfig;
import com.cnap.model.user.QuotaResponse;
import com.cnap.model.user.UserSysCommonResult;
import com.cnap.service.UserSysService;
import com.cnap.utils.JsonUtil;
import com.cnap.utils.TokenUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 类说明
 *
 * @author xc
 **/
@Service
public class UserSysServiceImpl implements UserSysService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserSysServiceImpl.class);
    private static final String QUERY_QUOTA = "/quota/getUserQuota";
    private static final String UPDATE_QUOTA = "/quota/updateUsedQuota";

    private final UserSysConfig userSysConfig;

    @Autowired
    public UserSysServiceImpl(UserSysConfig userSysConfig) {
        this.userSysConfig = userSysConfig;
    }

    @Override
    public boolean checkHasQuota(String userName) {
        if ("admin".equals(userName)) {
            // admin不需要配额限制
            return true;
        }
        String url = userSysConfig.getUrl() + QUERY_QUOTA;
        Map<String, String> param = new HashMap<>();
        param.put("userName", userName);

        String result = HttpUtil.post(url, JsonUtil.objectToJsonStr(param));
        UserSysCommonResult<QuotaResponse> res = JsonUtil.jsonStrToObject(result, new TypeReference<UserSysCommonResult<QuotaResponse>>() {
        });
        if (Objects.isNull(res)) {
            return false;
        }
        QuotaResponse response = res.getData();
        return Objects.nonNull(response) && Objects.nonNull(response.getAppSize()) && Integer.parseInt(response.getAppSize()) > 0;
    }

    @Override
    public void updateQuota(int changeAppNum, String userName, String type) {
        if ("admin".equals(userName)) {
            // admin不需要配额限制
            return;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("userName", userName);
        param.put("appSize", changeAppNum);
        param.put("type", type);

        String url = userSysConfig.getUrl() + UPDATE_QUOTA;
        try (HttpResponse response = HttpRequest.post(url).header("Authorization", TokenUtils.getTOKEN())
                .body(JsonUtil.objectToJsonStr(param)).execute();) {
            if (!response.isOk()) {
                LOGGER.error("[quota]: update quota fail, param={}", JsonUtil.objectToJsonStr(param));
                return;
            }
            LOGGER.info("[quota]: update quota success, param={}", JsonUtil.objectToJsonStr(param));
        }
    }
}
